package com.example.cofeed.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ObjectUtils;
import  com.example.cofeed.util.ToastUtils;;
import com.example.cofeed.activity.SupplyDetailsActivity;
import com.example.cofeed.activity.WebViewActivity;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.entity.Supply;
import com.example.cofeed.even.LoginEeven;
import com.example.cofeed.even.RefreshEven;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.example.cofeed.R;
import com.example.cofeed.adapter.DemandAdapter;
import com.example.cofeed.base.BaseFragment;
import com.example.cofeed.widget.SpaceItemDecoration;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author mqwang
 */
public class DemandListFragment extends BaseFragment implements OnRefreshLoadMoreListener {
    @BindView(R.id.et_search)
    EditText mEtSearch;
    @BindView(R.id.rv_list)
    RecyclerView mRecLv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private List<Supply> supplyList = new ArrayList<>();
    private DemandAdapter mDemandAdapter;
    private int mType;
    private int mCateId;
    private int mPage = 1;
    private View mNoData;
    private String mKeyWord;

    public static DemandListFragment newInstance(int type, int catid) {
        DemandListFragment fragment = new DemandListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentKeyConstant.TYPE, type);
        bundle.putInt(IntentKeyConstant.ID, catid);
        fragment.setArguments(bundle);
        return fragment;

    }

    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_demand_list, container, false);
        return view;
    }

    public void updateArguments(int type, int catid){
        mType = type;
        mCateId = catid;
    }
    @Override
    protected void initData() {

        mNoData = LayoutInflater.from(getActivity()).inflate(R.layout.include_no_data, (ViewGroup) mRecLv.getParent(), false);

        mRefreshLayout.setEnableRefresh(true);
        Bundle arguments = getArguments();
        if (ObjectUtils.isNotEmpty(arguments)){
            mType = arguments.getInt(IntentKeyConstant.TYPE);
            mCateId = arguments.getInt(IntentKeyConstant.ID);
        }

        mDemandAdapter = new DemandAdapter();
        mRecLv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecLv.addItemDecoration(new SpaceItemDecoration(0, DensityUtil.dp2px(5)));
        mRecLv.setAdapter(mDemandAdapter);

        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        mDemandAdapter.setOnItemClickListener((adapter, view, position) -> {
            Supply supply = (Supply) adapter.getData().get(position);
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra(IntentKeyConstant.ID, supply.id);
            intent.putExtra(IntentKeyConstant.URL, supply.urlpath);
            intent.putExtra(IntentKeyConstant.TYPE, -1);
            startActivity(intent);

        });

        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String key = mEtSearch.getText().toString();
//                    if (TextUtils.isEmpty(key)){
//                        ToastUtils.showShort("请输入关键字");
//                        return false;
//                    }
                    mKeyWord = key;
                    KeyboardUtils.hideSoftInput(v);

                    mPage = 1;
                    supplyList.clear();
                    getData(true);

                    return true;
                }
                return false;
            }
        });


//        getData(true);
        mRefreshLayout.autoRefresh();


    }

    private void getData(boolean isFirst){
        ApiService.supply_get_list(this, mPage, mType, mCateId, mKeyWord, new DialogCallback<LzyResponse<List<Supply>>>(isFirst? getActivity(): null) {
            @Override
            public void onSuccess(Response<LzyResponse<List<Supply>>> response) {
                if (ObjectUtils.isNotEmpty(response.body().data)){
                    mPage ++ ;
                    supplyList.addAll(response.body().data);
                }
                if (ObjectUtils.isEmpty(supplyList)){
                    getView().findViewById(R.id.layout_empty).setVisibility(View.VISIBLE);
                }else {
                    getView().findViewById(R.id.layout_empty).setVisibility(View.GONE);
                    mDemandAdapter.setNewData(supplyList);
                }
                finishRefresh(mRefreshLayout);

            }

            @Override
            public void onError(Response<LzyResponse<List<Supply>>> response) {
                super.onError(response);
                finishRefresh(mRefreshLayout);

            }
        });

    }


    @OnClick(R.id.tv_sx)
    public void onViewClicked() {
        String key = mEtSearch.getText().toString();
//        if (TextUtils.isEmpty(key)){
//            ToastUtils.showShort("请输入关键字");
//        }
        mKeyWord = key;
        KeyboardUtils.hideSoftInput(mEtSearch);

        mPage = 1;
        supplyList.clear();
        getData(true);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getData(false);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        supplyList.clear();
        getData(false);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(RefreshEven refreshEven){
        if (refreshEven.type == 1){
            mRefreshLayout.autoRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Login(LoginEeven loginEeven){
        mRefreshLayout.autoRefresh();

    }
}
